package com.ljl.ssm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.ljl.ssm.entity.*;
import com.ljl.ssm.mapper.OrderItemMapper;
import com.ljl.ssm.mapper.OrderMapper;
import com.ljl.ssm.mapper.ProductMapper;
import com.ljl.ssm.pojo.Collection;
import com.ljl.ssm.service.*;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 2019年7月8日 14:13:28
 */
@Controller
public class ForeController {


	@Autowired
	IProductService productService;
	@Autowired
	IUserService userService;
	@Autowired
	IOrderItemService orderItemService;
	@Autowired
	IOrderService orderService;
	@Autowired
	IReviewService iReviewService;
	@Autowired
	private ProductMapper productMapper;
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private OrderItemMapper orderItemMapper;

	@Autowired
	private ICollectionService collectionService;
	private Logger logger = Logger.getLogger(ForeController.class);




	/**
	 * 首页访问方法，给首页的JSP页面添加以下数据：
	 *
	 * @param model
	 * @return
	 */
	@RequestMapping("/home")
	public String home(Model model,HttpSession session) {
//		List<Category> categories = categoryService.list();
//		productService.fill(categories);
//		productService.fillByRow(categories);
//		List<ReferalLink> links = referalLinkService.listAll();
//
//		model.addAttribute("categories", categories);
//		model.addAttribute("links", links);

		PageInfo pageInfoT= productService.selectAll();
		session.setAttribute("pageInfoT", pageInfoT);
		session.setAttribute( "path","http://172.21.64.152:80/" );

			PageInfo pageL1 = productService.selectListbySize( 14, 1 );
			model.addAttribute( "pageL1", pageL1 );
			PageInfo pageL2 = productService.selectListbySize( 14, 2 );
			model.addAttribute( "pageL2", pageL2 );
			PageInfo pageL3 = productService.selectListbySize( 14, 3 );
			model.addAttribute( "pageL3", pageL3 );
			PageInfo pageL4 = productService.selectListbySize( 14, 4 );
			model.addAttribute( "pageL4", pageL4 );
			PageInfo pageL5 = productService.selectListbySize( 14, 5 );
			model.addAttribute( "pageL5", pageL5 );

		return "index";
	}


	@RequestMapping("shoucang")
	public String initshoucang(Model model,
							   @RequestParam(defaultValue = "1",value = "pn")Integer pn,
							   HttpSession session,
							   int product_id){
		User user=(User)session.getAttribute( "user" );
		if (user==null){
			return "login";
		}
		int user_id=user.getId();
		if(collectionService.select(user_id,product_id)==0){
			com.ljl.ssm.pojo.Collection collection=new Collection();
			collection.setUserId(user_id);
			collection.setProductId(product_id);

			collectionService.insert(collection);
		}


		return "redirect:showProduct?product_id=" + product_id;
	}

	@RequestMapping("quxiao")
	public String uncollection(Model model,
							   HttpSession session,
							   @RequestParam(defaultValue = "1",value = "pn")Integer pn,
							   Integer product_id){
		int user_id=((User)session.getAttribute( "user" )).getId();
		collectionService.delete(user_id,product_id);
		PageInfo pageInfo=collectionService.selectAll(user_id,pn);
		//System.out.println(pageInfo.getList());
		model.addAttribute(pageInfo);

		return "shoucang";
	}

	@RequestMapping("pageshoucang")
	public String soucahng(Model model,
						   HttpSession session,
						   @RequestParam(defaultValue = "1",value = "pn")Integer pn){

		int user_id=((User)session.getAttribute( "user" )).getId();
		PageInfo pageInfo=collectionService.selectAll(user_id,pn);

		model.addAttribute(pageInfo);
		return "shoucang";
	}

	@RequestMapping("/showProduct")
	public String showProduct(Model model, Integer product_id, HttpSession session) {

		Product product = productService.getById(product_id);
		User user=(User) session.getAttribute( "user" );
		if(user!=null){
			int user_id  = user.getId();
			if(collectionService.select(user_id,product_id)!=0){
				model.addAttribute( "collection",1 );
			}
		}
		model.addAttribute("product", product);
		System.out.println(product.toString());
//		List<PropertyValue> propertyValues = propertyValueService.listByProductId(product_id);
		model.addAttribute("propertyValues", 11);
//		List<Review> reviews = reviewService.listByProductId(product_id);
		model.addAttribute("reviews", "话");

		return "xiangqing";
	}

	@RequestMapping("/searchProduct")
	public String searchProduct(Model model, String keyword) {

//		PageHelper.offsetPage(0, 20);
		List<Product> products = productService.selectList(keyword);
//		for (Product product : products) {
//			product.setReviewCount(6);//写
//		}
		model.addAttribute("products", products);

		return "searchResult";
	}

	@RequestMapping("sortProduct")
	public String sortProduct(Model model, String sort, String keyword) {
		List<Product> products = productService.selectList(keyword);
//		for (Product product : products) {
//			product.setReviewCount(6);//写
//		}
//		if (null != sort) {
//			switch (sort) {
//				case "all":
//					Collections.sort(products, Comparator.comparing(Product::getSaleXReviewCount));
//					break;
//				case "reviewCount":
//					Collections.sort(products, Comparator.comparing(Product::getReviewCount));
//					break;
//				case "date":
////					Collections.sort(products, comparing(Product::get));
//					break;
//				case "sale":
//					Collections.sort(products, Comparator.comparing(Product::getSale));
//					break;
//				case "price":
//					Collections.sort(products, Comparator.comparing(Product::getPrice));
//					break;
//			}
//		}
		model.addAttribute("products", products);

		return "searchResult";
	}


	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		session.removeAttribute("user");
		return "redirect:home";
	}

	@RequestMapping("/register")
	public String register(Model model, User user) {
		String name = user.getName();
		boolean exist = userService.isExist(name);

		if (exist) {
			String msg = "用户名已经被占用，不能使用";
			model.addAttribute("msg", msg);
			model.addAttribute("username", user.getName());
			return "registerPage";
		}
		userService.add(user);

		return "redirect:registerSuccessPage";
	}


	/**
	 * 立即购买（即新增OrderItem项）需要考虑以下两种情况：
	 * 1.如果这个产品已经存在于购物车中，那么只需要相应的调整数量就可以了
	 * 2.如果不存在对应的OrderItem项，那么就新增一个订单项（OrderItem）
	 * - 前提条件：已经登录
	 *
	 * @param session    session用于获取user信息
	 * @return
	 */
	@RequestMapping("/buyone")
	public String buyone(Integer product_id, Integer number, HttpSession session) {
		Product product = productService.getById(product_id);
		int orderItemId = 0;

		User user = (User) session.getAttribute("user");
		boolean found = false;
		List<OrderItem> orderItems = orderItemService.listByUserId(user.getId());
		for (OrderItem orderItem : orderItems) {
			if (orderItem.getProductId().intValue() == product.getId().intValue()) {
				orderItem.setNumber(orderItem.getNumber() + number);
				orderItemService.update(orderItem);
				orderItemId = orderItem.getId();
				break;
			}
		}
		if (!found) {
			OrderItem orderItem = new OrderItem();
			orderItem.setUserId(user.getId());
			orderItem.setNumber(number);
			orderItem.setProductId(product_id);
			orderItemService.add(orderItem);
			orderItemId = orderItem.getId();
		}
		return "redirect:buy?orderItemId=" + orderItemId;
	}

	@RequestMapping("buy")
	public String buy(Model model, String[] orderItemId, HttpSession session) {
		List<OrderItem> orderItems = new ArrayList<>();
		float total = 0;
		for (String strId : orderItemId) {
			int id = Integer.parseInt(strId);
			OrderItem oi = orderItemService.getById(id);
			total += oi.getProduct().getPrice() * oi.getNumber();
			orderItems.add(oi);
		}
		session.setAttribute("orderItems", orderItems);
		model.addAttribute("total", total);
		return "buyPage";
	}

	@RequestMapping("createOrder")
	@ResponseBody
	public ModelAndView createOrder(Model model, @ModelAttribute Order order, HttpSession session, BindingResult result) {
		User user = (User) session.getAttribute("user");
		String orderCode = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
		order.setUserId(user.getId());
		order.setReceiver(user.getName());
		order.setOrderCode(orderCode);
		order.setCreateDate(new Date());
		order.setUserId(user.getId());
		order.setStatus(IOrderService.waitPay);
		List<OrderItem> orderItems = (List<OrderItem>) session.getAttribute("orderItems");
		float post = 0;
		for(OrderItem ois : orderItems){
			post +=  ois.getNumber()*ois.getProduct().getPrice();
		}
		order.setPost(post+"");
		orderMapper.insert(order);
		ModelAndView mv = new ModelAndView("alipay");
		mv.addObject("order", order);
		return mv;
	}

	@RequestMapping("payed")
	public String payed(int order_id, float total, Model model) {
		Order order = orderService.get(order_id);
		order.setStatus(orderService.waitDelivery);
		order.setPayDate(new Date());
		orderService.update(order);
		model.addAttribute("o", order);
		return "payed";
	}

	/**
	 * 加入购物车方法，跟buyone()方法有些类似，但返回不同
	 * 仍然需要新增订单项OrderItem，考虑两个情况：
	 * 1.如果这个产品已经存在于购物车中，那么只需要相应的调整数量就可以了
	 * 2.如果不存在对应的OrderItem项，那么就新增一个订单项（OrderItem）
	 * - 前提条件：已经登录
	 *
	 * @param product_id
	 * @param num
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping("/addCart")
	@ResponseBody
	public String addCart(int product_id, int num, Model model, HttpSession session) {
		Product p = productService.get(product_id);
		User user = (User) session.getAttribute("user");
		boolean found = false;

		List<OrderItem> ois = orderItemService.listByUserId(user.getId());
		for (OrderItem oi : ois) {
			if (oi.getProduct().getId().intValue() == p.getId().intValue()) {
				oi.setNumber(oi.getNumber() + num);
				orderItemService.update(oi);
				found = true;
				break;
			}
		}
		if (!found) {
			OrderItem oi = new OrderItem();
			oi.setUserId(user.getId());
			oi.setNumber(num);
			oi.setProductId(product_id);
			orderItemService.add(oi);
		}
		return "success";
	}

	/**
	 * 查看购物车方法：
	 * 1.首先通过session获取到当前的用户
	 * 2.获取这个用户关联的订单项的集合
	 *
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping("/Cart")
	public String cart(Model model, HttpSession session) {
		User user = (User) session.getAttribute("user");
		List<OrderItem> orderItems = orderItemService.listForCart(user.getId());
		model.addAttribute("orderItems", orderItems);
		return "gouwuche";
	}

	@RequestMapping("/checkLogin")
	@ResponseBody
	public String checkLogin(HttpSession session) {
		User user = (User) session.getAttribute("user");
		if (null != user)
			return "success";
		return "fail";
	}

	@RequestMapping("changeOrderItem")
	@ResponseBody
	public String changeOrderItem(Model model, HttpSession session, int productId, int number) {
		User user = (User) session.getAttribute("user");
		if (null == user)
			return "fail";

		List<OrderItem> ois = orderItemService.listByUserId(user.getId());
		for (OrderItem oi : ois) {
			if (oi.getProduct().getId().intValue() == productId) {
				oi.setNumber(number);
				orderItemService.update(oi);
				break;
			}
		}
		return "success";
	}

	@RequestMapping("deleteOrderItem")
	@ResponseBody
	public String deleteOrderItem(Model model, HttpSession session, Integer orderItemId) {
		User user = (User) session.getAttribute("user");
		if (null == user)
			return "fail";
		orderItemService.delete(orderItemId);
		return "success";
	}

	@RequestMapping("bought")
	public String bought(Model model, HttpSession session) {
		User user = (User) session.getAttribute("user");

		List<Order> orders = orderMapper.selectList(
				new QueryWrapper<Order>()
						.eq("user_id",user.getId())
						.ne("status",IOrderService.delete)
		);
		model.addAttribute("orders", orders);
		return "bought";
	}

	@RequestMapping("confirmPay")
	public String confirmPay(Model model, Integer order_id) {
		Order order = orderService.get(order_id);
		orderItemService.fill(order);
		model.addAttribute("order", order);
		return "confirmPay";
	}

	@RequestMapping("orderConfirmed")
	public String orderConfirmed(Model model, Integer order_id) {
		Order o = orderService.get(order_id);
		o.setStatus(IOrderService.waitReview);
		o.setConfirmDate(new Date());
		orderService.update(o);
		return "orderConfirmedPage";
	}

	@RequestMapping("deleteOrder")
	@ResponseBody
	public String deleteOrder(Model model, Integer order_id) {
		Order o = orderService.get(order_id);
		o.setStatus(IOrderService.delete);
		orderService.update(o);
		return "success";
	}
//
//	@RequestMapping("review")
//	public String review(Model model, Integer order_id) {
//		Order order = orderService.get(order_id);
//		orderItemService.fill(order);
//		Product product = order.getOrderItems().get(0).getProduct();
//		List<Review> reviews = iReviewService.l listByProductId(product.getId());
//		productService.setReviewCount(product);
//		model.addAttribute("product", product);
//		model.addAttribute("order", order);
//		model.addAttribute("reviews", reviews);
//		return "reviewPage";
//	}

//	@RequestMapping("doreview")
//	public String doreview(Model model, HttpSession session,
//                           @RequestParam("order_id") Integer order_id,
//                           @RequestParam("product_id") Integer product_id,
//                           String content) {
//
//		Order order = orderService.get(order_id);
//		order.setStatus(OrderService.finish);
//		orderService.update(order);
//
//		User user = (User) session.getAttribute("user");
//		Review review = new Review();
//		review.setContent(content);
//		review.setProduct_id(product_id);
//		review.setCreateDate(new Date());
//		review.setUser_id(user.getId());
//		reviewService.add(review);
//
//		return "redirect:review?order_id=" + order_id + "&showonly=true";
//	}

}
